import React from 'react';
import ReactDOM from 'react-dom';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { WeaTable, WeaTools, WeaTop, WeaTab, WeaSearchGroup, WeaDialog } from 'ecCom';
import { WeaRightMenu, WeaPopoverHrm, WeaLeftRightLayout, WeaLeftTree, WeaReqTop } from 'ecCom';
import { Icon, Button, Form, Spin, Menu, Dropdown, Tabs, Select, notification, BackTop, Alert, Modal } from 'antd';
import FormLayout from './FormLayout';
import NoRight from './NoRight';
import ImportDetail from './ImportDetail';
import ModeShare from './ModeShare';
import Reply from './reply/Reply';
const FormItem = Form.Item;
const MenuItem = Menu.Item;
import * as Actions from '../../actions/card';
import * as formAction from '../../actions/form';
import equal from 'deep-equal';
import * as API from '../../apis/card';
import * as Util from '../../util/modeUtil';
import * as lodash from 'lodash';

import "../../style/mode.css";
import "../../style/tab.css";

const TabPane = Tabs.TabPane;
const Option = Select.Option;

/**
 * 建模卡片页面总入口
 */
class Card extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
        }
    }

    componentDidMount() {
        this.init();
    }

    componentDidUpdate() {
        //渲染完毕后 初始化所有js    布局js、按钮js、页面扩展js等
        Util.initJs(this.props.rightmenu, this.props.mainFields, this.props.modeField, this);
    }

    //页面加载 初始化模块相关信息
    init = () => {
        const { actions, billid, modeId, formId, type, layoutid, customid, viewfrom, opentype, fromSave, iscreate } = this.props;
        actions.initPage({ billid: billid ? billid : "0", modeId, formId, type, layoutid, customid, viewfrom, opentype, fromSave, iscreate });
        //actions.getLayoutBase({ billid, modeId, formId, type, layoutid, customid, viewfrom, opentype, fromSave, iscreate });   
    }

    shouldComponentUpdate(nextProps) {
        return true;
    }

    //Form表单原生提交方式 暂不使用
    handleSubmit = (e) => {
        //e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                //console.log('Received values of form: ', values);
            }
        });
    }

    /**
     * 所有页面扩展、按钮方法入口，控件传参数限制 采用统一入口
     */
    excute = (btntype, id, issystemflag) => {
        if (btntype == "1")
            this.doedit(id, issystemflag);
        else if (btntype == "2")
            this.doSubmit(id, issystemflag, btntype);
        else if (btntype == "3")
            this.doSubmit(id, issystemflag, btntype);
        else if (btntype == "5")
            this.importDetail(id, issystemflag);
        else if (btntype == "7")
            this.toDel(id, issystemflag);
        else if (btntype == "11")
            this.doShare(id, issystemflag);
        else if (btntype == "13")
            this.doPrint(id, issystemflag);
        else if (btntype == "17")
            this.viewLog(id, issystemflag);
        else if (btntype == "19")
            this.doClear(id, issystemflag);
        else if (btntype == "23")
            this.createQRCode(id, issystemflag);
        else if (btntype == "29")
            this.createBARCode(id, issystemflag);
        else if (btntype == "31")
            this.doBack(id, issystemflag);
        else if (btntype == "37")
            this.doViewBack(id, issystemflag);
        else if (btntype == "53")
            this.windowOpenOnSelf(id, issystemflag);
        else if (btntype == "59")
            this.windowOpenOnNew(id, issystemflag);
        else if (btntype == "61")
            this.doCustomFunction(id, issystemflag);

    }
    //编辑---------------1
    doedit = (id, issystemflag) => {
        const { actions, billid, modeId, formId, layoutid, customid, viewfrom, opentype, fromSave, iscreate } = this.props;
        actions.getLayoutBase({ billid, modeId, formId, type: "2", customid, viewfrom, opentype, fromSave, iscreate });
    }
    //btntype 保存---------------2
    //btntype 保存并新建---------------3
    doSubmit = (id, issystemflag, btntype) => {
        //必填校验
        if (!Util.check_form(needcheck, this.props.mainFields, this.props.detailData)) {
            return false;
        }
        //checkCustomize校验
        if (typeof (checkCustomize) == 'function') {
            try {
                var flag = checkCustomize();
                if (!flag) {
                    return false;
                }
            } catch (e) {
                return false;
            }
        }
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                const { actions, billid, layoutid, formId, modeId, type, istabinline, mainData, tabcount, templateid, opentype, customid, isfromTab, tabid, bviewfrom, fromSave, detailData } = this.props;
                let isFormMode = "1";
                let iscreate = type;
                let src = type == 1 ? "submit" : "save";
                let currentLayoutId = layoutid;

                var o = jQuery("#modeForm").serializeArray();
                var data = {};
                for (var i = 0; i < o.length; i++) {
                    data[o[i].name] = o[i].value;
                }
                for (var item in values) {
                    if (!data[item]) {
                        data[item] = values[item];
                    }
                }
                /*for (var item in mainData.data) {
                    if (!data["field" + item]) {
                        data["field" + item] = mainData.data[item].value;
                    }
                }
                for (var tablename in detailData.data) {
                    let tableObj = detailData.data[tablename];
                    for (let i = 0; i < tableObj.data.length; i++) {
                        let rowObj = tableObj.data[i];
                        for (var item in rowObj) {
                            if (!data["field" + item+"_"+i]) {
                                data["field" + item+"_"+i] = rowObj[item].value;
                            }
                        }
                    }
                }
                //把mainData detailData 封装 暂时不用
                console.log(data);*/
                //data = lodash.merge(data, values);
                //开始封装子表参数
                for (let item in detailData.data) {
                    let tableData = detailData.data[item].data;
                    let ta = item.split("_");
                    let tableIndex = parseInt(ta[1] - 1);
                    data["modesnum" + tableIndex] = tableData.length;
                    data["indexnum" + tableIndex] = tableData.length;
                    let submitdtlid = "";
                    for (let i = 0; i < tableData.length; i++) {
                        if (tableData[i].id) {
                            data["dtl_id_" + tableIndex + "_" + i] = tableData[i].id.value;
                        }
                        submitdtlid += "," + i;
                    }
                    data["submitdtlid" + tableIndex] = submitdtlid == "" ? "" : submitdtlid.substring(1);
                }
                //子表参数封装完毕

                actions.doSubmit({
                    btntype, billid, layoutid, formId, modeId, type, istabinline, tabcount, templateid,
                    opentype, customid, isfromTab, tabid, isFormMode, iscreate, src, currentLayoutId, bviewfrom, fromSave,
                    JSONStr: JSON.stringify(data),//表单数据 包含主表及明细表数据  以及子表属性参数
                    detail: JSON.stringify(detailData)//子表信息集合 备用
                })

            }
        });
    }
    //子表导入-----------------5
    importDetail = (id, issystemflag) => {
        alert(this.props.billid)
        if (this.props.billid == "0") {
            confirm({
                title: '您还未保存数据，是否保存',
                onOk() {
                    doSubmit = (id, issystemflag, "5");
                },
                onCancel() { },
            });
        } else {
            this.props.actions.showImportDetail(true);
        }
    }
    //删除---------------------7
    toDel = (id, issystemflag) => {
        parent.close();
        //this.props.actions.del();
    }
    //共享---------------------11
    doShare = (id, issystemflag) => {
        this.props.actions.showShare(true);
    }
    //打印---------------------13
    doPrint = (id, issystemflag) => {
        const { rightmenu } = this.props;
        let isfromTab = (rightmenu ? (rightmenu.haveTab ? "1" : "0") : this.props.isfromTab);
        let url = "/formmode/view/FormModePrint.jsp?isfromTab=" + isfromTab + "&modeId=" + this.props.modeId +
            "&formId" + this.props.formId + "&type=4&billid=" + this.props.billid + "&viewfrom=" + this.props.viewfrom + "&opentype=" + this.props.opentype + "&customid=" + this.props.customid;
        window.open(url);
    }
    //日志---------------------17
    viewLog = (id, issystemflag) => {
        window.open("/#/formmode/loglist?modeId=" + this.props.modeId + "&billid=" + this.props.billid + "&modename=" + this.props.modename);
    }
    //清空条件-----------------19
    doClear = (id, issystemflag) => { }
    //生成二维码---------------23
    createQRCode = (id, issystemflag) => {

        this.props.actions.show(false, true);

        /*if (this.props.modeInfo.qrIsuse == "1") {
            try {
                let params = {
                    title: "生成二维码",
                    url: "/formmode/view/QRCodeView.jsp?modeId=" + this.props.modeId + "&formId=" + this.props.formId + "&customid=" + this.props.customid + "&billid=" + this.props.billid,
                    style: { width: 400, height: 200 }
                }
                window.initWeaDialog(params)
                window.showWeaDialog();
            } catch (e) { alert(e) }
        } else {
            alert("二维码功能尚未开启，请在后台开启二维码功能");
        }*/
    }
    //生成条形码-------------29
    createBARCode = (id, issystemflag) => {

        this.props.actions.show(true, false);

        /*if (this.props.modeInfo.barIsused == "1") {
            try {
                let params = {
                    title: "生成条形码",
                    url: "/formmode/view/BARCodeView.jsp?modeId=" + this.props.modeId + "&formId=" + this.props.formId + "&customId=" + this.props.customid + "&billId=" + this.props.billid,
                    style: { width: 400, height: 150 }
                }
                window.initWeaDialog(params)
                window.showWeaDialog();
            } catch (e) { alert(e) }
        } else {
            alert("条形码功能尚未开启，请在后台开启条形码功能");
        }*/
    }
    //编辑返回-------------31
    doBack = (id, issystemflag) => {
        const { actions, billid, modeId, formId, layoutid, customid, viewfrom, opentype, fromSave, iscreate } = this.props;
        actions.getLayoutBase({ billid, modeId, formId, type: "0", customid, viewfrom, opentype, fromSave, iscreate });
    }
    //查看返回-------------37
    doViewBack = (id, issystemflag) => {
        if (this.props.viewfrom == "fromsearchlist" & this.props.opentype == "1" && this.props.isfromTab == "1") {
            window.parent.location = "/formmode/search/CustomSearchBySimpleIframe.jsp?customid=" + this.props.customid;
        } else {
            window.location = "/formmode/search/CustomSearchBySimpleIframe.jsp?customid=" + this.props.customid;
        }
    }
    //默认窗口，当前窗口----53
    windowOpenOnSelf = (id, issystemflag) => {
        const { billid, modeId } = this.props;
        API.menuAction({ billid, modeId, pageexpandid: id }).then(({ api_errormsg, api_status }) => {
            if (api_status) {
                var url = eval("url_id_" + detailid);
                var thisWin = window;
                var parentWin = thisWin.parent;
                var href = parent.location.href;
                if (href.indexOf("AddFormMode.jsp") != -1) {
                    thisWin = thisWin.parent;
                    parentWin = thisWin.parent.parent;
                }
                if (this.props.isfromTab == "1") {
                    parentWin.location.href = url;
                } else {
                    thisWin.location.href = url;
                }
            }
        });
    }
    //弹出窗口------------59
    windowOpenOnNew = (id, issystemflag) => {
        const { billid, modeId } = this.props;
        API.menuAction({ billid, modeId, pageexpandid: id }).then(({ api_errormsg, api_status }) => {
            if (api_status) {
                var redirectUrl = eval(eval("url_id_" + id));
                var width = screen.availWidth - 10;
                var height = screen.availHeight - 50;
                var szFeatures = "top=0,";
                szFeatures += "left=0,";
                szFeatures += "width=" + width + ",";
                szFeatures += "height=" + height + ",";
                szFeatures += "directories=no,";
                szFeatures += "status=yes,toolbar=no,location=no,";
                szFeatures += "menubar=no,";
                szFeatures += "scrollbars=yes,";
                szFeatures += "resizable=yes"; //channelmode
                window.open(redirectUrl, "", szFeatures);
            }
        });
    }
    //其它--------------61
    doCustomFunction = (id, issystemflag) => {
        const { billid, modeId } = this.props;
        API.menuAction({ billid, modeId, pageexpandid: id }).then(({ api_errormsg, api_status }) => {
            if (api_status) {
                eval(eval("url_id_" + id));
            }
        });
    }

    /**
     * 所有按钮菜单、顶部快捷菜单点击事件入口
     */
    handleRightMenuClick = (key) => {
        const { rightmenu } = this.props;
        let btntype = rightmenu.RCMenu[key].btntype;
        let detailid = rightmenu.RCMenu[key].detailid;
        let issystemflag = rightmenu.RCMenu[key].issystemflag;
        this.excute(btntype, detailid, issystemflag)
    }

    /**
     * 添加行的方法  现在的逻辑是直接在调用的detailTable的addObj对象操作detailData数据 加一组明细并重新渲染  
     * addObj对象页面init时封装好 changeField方法可能会在字段值计算的时候改变addObj中字段的值
     * tablename 添加明细的表名
     * initialData 被添加的明细行字段初始值 传入JSON  格式 字段id：value    默认添加明细的值会从detailTable取addObj  initialData会追加到addObj中
     */
    addrow = (tablename, initialData) => {
        this.props.actions.addrow(tablename, initialData);
    }

    /**
     * 删除行的方法 现在的逻辑是直接从detailData中把需要删除的对象删掉 并重新渲染
     */
    delrow = (tablename) => {
        this.props.actions.delrow(tablename);
        //this.forceUpdate();//手动强制重新渲染页面  暂时不需要
    }

    /**
     * 复制行方法
     */
    copyRow = (tablename) => {
        this.props.actions.copyRow(tablename);
    }

    /**
     * 明细行选中、全选方法
     */
    checkRow = (symbol, drowIndex, value) => {
        let mainData = jQuery.extend(true, {}, this.props.mainData);
        let detailData = jQuery.extend(true, {}, this.props.detailData);
        let mainFields = jQuery.extend(true, {}, this.props.mainFields);
        if (drowIndex == "all") {
            for (let i = 0; i < detailData.data[symbol].data.length; i++) {
                detailData.data[symbol].data[i].isChecked = value;
            }
        } else {
            detailData.data[symbol].data[drowIndex].isChecked = value;
        }
        this.props.actions.changeField({ mainData, detailData, mainFields });
    }


    /**
     * 附件上传 根据E9上传组建 上传现分两步 第一步通过组建直接上传 成功后返回附件id然后通过fileUpload方法获取附件信息重新渲染页面
     */
    fileUpload = (symbol, detailIndex, fieldid, detailtype, fieldvalue) => {
        let mainData = jQuery.extend(true, {}, this.props.mainData);
        let detailData = jQuery.extend(true, {}, this.props.detailData);
        let mainFields = jQuery.extend(true, {}, this.props.mainFields);
        let isprint = this.props.isprint;
        this.props.actions.getUploadFileInfo({ symbol, detailIndex, fieldid, detailtype, fieldvalue, mainData, detailData, mainFields, isprint });
    }

    /**
     * 所有字段值变化方法
     * 所有页面字段联动方法的总入口 字段联动、公式、行列规则等都从这里执行
     * 同时可以触发dom元素的 bindproperchange方法
     * 目前只能监控到直接在网页中修改的内容 js赋值方式(布局js)修改暂时无法处理 待讨论
     */
    changeField = (fieldObj, value, symbol, drowIndex) => {
        //dispatch 的对象克隆一个同样的对象避免影响之前生命周期
        let mainData = jQuery.extend(true, {}, this.props.mainData);
        let detailData = jQuery.extend(true, {}, this.props.detailData);
        let mainFields = jQuery.extend(true, {}, this.props.mainFields);
        let detailTable = this.props.detailTable;
        let data = Util.changeField(fieldObj, value, symbol, drowIndex, mainData, detailData, mainFields, this.props);
        this.props.actions.changeField(data);
    }

    /**
     * 显示属性联动方法  已废弃 统一迁移到changeField中
     */
    changeshowattr = (value, id, tableName, dataIndex) => {
        const { actions, mainFields, modeField } = this.props
        if (tableName == "emaintable") {//如果是主表字段
            alert("field" + id);
            let fieldvalue = this.props.form.getFieldValue("field" + id);
            alert(fieldvalue);
        }
    }

    getInitialState() {
        return {
            tabPosition: 'top',
        };
    }

    changeTabPosition(tabPosition) {
        this.setState({ tabPosition });
    }

    /**
     * 顶部页面扩展组 点击事件 受控件限制 处理方式跟之前略有不同 现在点击组的时候会默认加载一次该组中的第一个页面扩展 
     */
    handleMenuClick = (e) => {
        if (e.key) {
            let key = e.key.split("_");
            let groupid = key[0];
            let tabid = key[1];
            let hreftitle = this.props.rightmenu.topTab["group" + groupid].groups[tabid].hreftitle;
            let hreftarget = this.props.rightmenu.topTab["group" + groupid].groups[tabid].hreftarget;
            jQuery("#group" + groupid + "iframe").attr("src", hreftarget);
            jQuery("#group" + groupid).html(hreftitle)
        }
    }

    render() {
        const { loading, isRight, isEdit, billid, modeId, formId, type, layoutid } = this.props;
        if (loading != "loading" && !isRight) {
            return <NoRight />

        }
        const { getFieldProps } = this.props.form;
        const { customid, isexcel, isImportDetail, modename, modedesc, custompage, istabinline, isfromTab } = this.props;
        const { datajson, rightmenu, modeInfo, modeField, orderlyjson } = this.props;
        const { searchAdvanceVisible = false, showSearchDrop = false } = this.props;
        const { mainFields, detailTable } = this.props;
        const { mainData, detailData, initValue } = this.props;
        const { showReply, replyList, replyFieldList, replyModeInfo, replyData, replyType, showType, replySearchData, top, replyIndex, dataLength, replyListData } = this.props;
        const { showBottom, showX, showY, replyShowType, dataIndex, total, current, pagesize } = this.props;
        //传递给子元素的方法集合 所有子组建中调用的页面逻辑方法集合
        const functionAttr = {}
        functionAttr.addrow = this.addrow;
        functionAttr.delrow = this.delrow;
        functionAttr.changeshowattr = this.changeshowattr;
        functionAttr.fileUpload = this.fileUpload;
        functionAttr.changeField = this.changeField;
        functionAttr.checkRow = this.checkRow;
        functionAttr.copyRow = this.copyRow;

        const eformdesign = datajson ? datajson.eformdesign : null;
        const etables = eformdesign ? eformdesign.etables : null;
        const emaintable = etables ? etables.emaintable : null
        const colheads = emaintable ? emaintable.colheads : null;
        const rowheads = emaintable ? emaintable.rowheads : null;
        const colattrs = emaintable ? emaintable.colattrs : null;
        const rowattrs = emaintable ? emaintable.rowattrs : null;
        const ec = emaintable ? emaintable.ec : null;
        const backgroundImage = emaintable ? emaintable.backgroundImage : null;
        const floatingObjectArray = emaintable ? emaintable.floatingObjectArray : null;
        const ecMap = {};
        if (ec) {
            for (let i = 0, l = ec.length; i < l; i++) {
                let cellObj = ec[i];
                let key = cellObj.id;
                ecMap[key] = cellObj;
            }
        }

        const dropMenuDatas = new Array();                              //右键菜单
        const btns = new Array();                                       //快捷按钮
        const tabs = new Array();                                       //内嵌页面扩展
        const topTabs = new Array();                                    //顶部页面扩展（包含扩展组）
        const Rcmenu = rightmenu ? rightmenu.RCMenu : null;
        const quickButton = rightmenu ? rightmenu.quickButton : null;
        const innerTab = rightmenu ? rightmenu.innerTab : null;
        const topTab = rightmenu ? rightmenu.topTab : null;

        let height = (document.body.clientHeight - 40) + "px";
        let height1 = document.body.clientHeight + "px";
        if (Rcmenu) {
            for (var i = 0; i < Rcmenu.length; i++) {
                let menuObj = Rcmenu[i];
                dropMenuDatas.push({
                    key: i,
                    disabled: false,
                    icon: <i className='icon-search' />,
                    content: menuObj.menuName
                });
            }
        }

        if (quickButton) {
            for (var i = 0; i < quickButton.length; i++) {
                let btnObj = quickButton[i];
                btns.push(<Button
                    type="primary"
                    disabled={false}
                    onClick={() => this.excute(btnObj.btntype, btnObj.detailid, btnObj.issystemflag)}>
                    {btnObj.quickname}
                </Button>);
            }
        }
        if (innerTab) {
            for (var i = 0; i < innerTab.length; i++) {
                let tabObj = innerTab[i];
                tabs.push(
                    <TabPane tab={tabObj.expendname} key={i + 2}>
                        <iframe
                            src={tabObj.hreftarget}
                            border="0"
                            width="100%"
                            frameborder="0"
                            height={height} >
                        </iframe>
                    </TabPane>
                );
            }
        }
        if (topTab) {
            for (var item in topTab) {
                let topObj = topTab[item];
                if (item.indexOf("group") != -1) {
                    let groupid = topObj.groupid;
                    let groupname = topObj.groupname;
                    let groups = topObj.groups;
                    let groupDefaultHref = "";
                    let itemArr = new Array();
                    for (let gitem in groups) {
                        let groupObj = groups[gitem];
                        let detailid = groupObj.detailid;
                        let expendname = groupObj.expendname;
                        groupDefaultHref = groupDefaultHref == "" ? groupObj.hreftarget : groupDefaultHref;
                        let hreftitle = groupObj.hreftitle;
                        let key = groupid + "_" + detailid;
                        itemArr.push(<Menu.Item key={key}>{hreftitle}</Menu.Item>);
                    }
                    let menu = (
                        <Menu onClick={this.handleMenuClick}>
                            {itemArr}
                        </Menu>
                    )

                    let groupHandle = <Dropdown overlay={menu} trigger="click">
                        <span className="ant-dropdown-link" href="#">
                            <span id={item}>{groupname}</span> <Icon type="down" />
                        </span>
                    </Dropdown>

                    topTabs.push(<TabPane tab={groupHandle} key={item}>
                        <iframe
                            src={groupDefaultHref}
                            id={item + "iframe"}
                            border="0"
                            width="100%"
                            frameborder="0"
                            height={height1} >
                        </iframe>
                    </TabPane>)
                }
            }
        }

        //布局主体内容（包含内嵌页面扩展）
        let mainForm = <WeaRightMenu
            datas={dropMenuDatas}
            width={200}
            onClick={this.handleRightMenuClick}
        >
            <WeaTop
                title={modename}
                loading='loading'
                icon={<i className='icon-portal-workflow' />}
                iconBgcolor='#55D2D4'
                buttons={btns}
                buttonSpace={10}
                showDropIcon={true}
                dropMenuDatas={dropMenuDatas}
                onDropMenuClick={this.handleRightMenuClick}
                style={{ height: "auto" }}
            >
                {loading == "loading" &&
                    <div style={{ textAlign: "center", borderRadius: 4, marginBottom: 20, padding: "30px 50px", margin: "20px 0" }}>
                        <Spin />&nbsp;&nbsp;&nbsp;<Spin />&nbsp;&nbsp;&nbsp;<Spin />
                    </div>
                }
                {loading == "loaded" && <Tabs tabPosition={this.state.tabPosition}>
                    <TabPane tab={modename} key="1">

                        <Form horizontal
                            className="modeForm"
                            name="modeForm"
                            id="modeForm"
                            onSubmit={this.handleSubmit}
                        >
                            <FormLayout
                                getFieldProps={getFieldProps}
                                symbol="emaintable"
                                className="excelMainTable"
                                modeInfo={modeInfo}
                                type={type}
                                etables={etables}
                                colheads={colheads}
                                rowheads={rowheads}
                                rowattrs={rowattrs}
                                colattrs={colattrs}
                                ecMap={ecMap}
                                mainFields={mainFields}
                                detailTable={detailTable}
                                mainData={mainData.data}
                                detailData={detailData.data}
                                functionAttr={functionAttr}
                                modeField={modeField}
                                orderlyjson={orderlyjson}
                                backgroundImage={backgroundImage}
                                floatingObjectArray={floatingObjectArray}
                                actions={this.props.actions}
                            />
                        </Form>
                        {showReply && type == "0" &&
                            <Reply
                                actions={this.props.actions}
                                replyList={replyList}//评论结果集合 
                                replyFieldList={replyFieldList}//评论表单字段 
                                modeId={modeId}
                                formId={formId}
                                billid={billid}
                                replyModeInfo={replyModeInfo}//回复评论模块信息
                                replyData={replyData}//回复内容数据
                                replyType={replyType}//回复附加功能是否显示
                                showType={showType}//高级搜索是否展开
                                replySearchData={replySearchData}//高级搜索条件
                                top={top}//点击对象的位置高度 暂时不用
                                replyIndex={replyIndex}//正在编辑、引用、评论的记录的id
                                replyListData={replyListData}//明细列表数据集合
                                showBottom={showBottom}//是否显示评论下拉区域
                                showX={showX}
                                showY={showY}
                                replyShowType={replyShowType}
                                dataIndex={dataIndex}
                                total={total}
                                current={current}
                                pagesize={pagesize}
                            />
                        }
                        <BackTop style={{ bottom: 100 }}>
                            <div style={{
                                height: 40,
                                width: 40,
                                lineHeight: '40px',
                                borderRadius: 4,
                                backgroundColor: '#57c5f7',
                                color: '#fff',
                                textAlign: 'center',
                                fontSize: 20,
                            }}>UP</div>
                        </BackTop>
                    </TabPane>
                    {tabs}
                </Tabs>}

            </WeaTop>
        </WeaRightMenu>;

        let otherS = <div><WeaPopoverHrm />
            {this.props.modeInfo && this.props.modeInfo.barIsused == "1" &&
                <WeaDialog
                    visible={this.props.showBar}
                    title="生成条形码"
                    url={"/formmode/view/BARCodeView.jsp?modeId=" + this.props.modeId + "&formId=" + this.props.formId + "&customId=" + this.props.customid + "&billId=" + this.props.billid}
                    style={{ width: 400, height: 150 }}
                    closable={true}
                    onCancel={() => { this.props.actions.show(false, false); }}
                />
            }
            {this.props.modeInfo && this.props.modeInfo.qrIsuse == "1" &&
                <WeaDialog
                    visible={this.props.showQr}
                    title="生成二维码"
                    url={"/formmode/view/QRCodeView.jsp?modeId=" + this.props.modeId + "&formId=" + this.props.formId + "&customid=" + this.props.customid + "&billid=" + this.props.billid}
                    style={{ width: 400, height: 200 }}
                    closable={true}
                    onCancel={() => { this.props.actions.show(false, false); }}
                />
            }
            <ImportDetail ref="importDetailDialog" title="明细导入" billid={billid} formId={formId} modeId={modeId} actions={this.props.actions} visible={this.props.showImport} excelData={this.props.excelData} />
            <ModeShare
                actions={this.props.actions}
                selectedRowKeys={this.props.selectedRowKeys}
                visible={this.props.showShare}
                title={modename}
                shareData={this.props.shareData}
                shareDataList={this.props.shareDataList}
                billid={billid}
                formId={formId}
                modeId={modeId}
            /></div>;
        let formDiv;
        if (istabinline == "1" || isfromTab == "1") {//如果是来自页面扩展 则不加载顶部页面扩展
            formDiv = <div>
                {otherS}
                {mainForm}
            </div>;
        } else {
            formDiv = <div>
                {otherS}
                <Tabs size="small">
                    <TabPane tab={modename} key="1000">
                        <WeaPopoverHrm />
                        {mainForm}
                    </TabPane>
                    {topTabs}
                </Tabs>
            </div>
        }
        return formDiv
    }
}

class MyErrorHandler extends React.Component {
    render() {
        const hasErrorMsg = this.props.error && this.props.error !== "";
        return (
            <WeaErrorPage msg={hasErrorMsg ? this.props.error : "对不起，该页面异常，请联系管理员！"} />
        );
    }
}

Card = WeaTools.tryCatch(React, MyErrorHandler, { error: "" })(Card);

Card = Form.create({

    onFieldsChange(props, fields) {
        //console.log(props,fields)
        const { actions, modeField } = props;
        let mainData = jQuery.extend(true, {}, this.props.mainData);
        let detailData = jQuery.extend(true, {}, this.props.detailData);
        let mainFields = jQuery.extend(true, {}, this.props.mainFields);
        for (var item in fields) {
            let reg = new RegExp("^_");
            if (!reg.test(item)) {//不是明细表 checkbox
                let fieldValue = fields[item].value;

                if (item.indexOf("_") > 0) {
                    let fid = item.substring(5);
                    let fa = fid.split("_");
                    let fieldid = fa[0];
                    let rowindex = parseInt(fa[1]);
                    let tablename = mainFields[fieldid].detailtable;
                    let data = detailData.data[tablename].data[rowindex];
                    data[fieldid].value = fieldValue;
                    detailData.data[tablename].data[rowindex] = data;
                } else {
                    let fieldid = item.substring(5);
                    mainData.data[fieldid].value = fieldValue;
                }
            } else {
                let fa = item.split("_");
                let tablename = "detail_" + fa[2];
                let rowIndex = parseInt(fa[3]);
                let fieldValue = fields[item].value;
                detailData.data[tablename].data[rowIndex].isChecked = fieldValue;
            }
        }

        actions.changeField({ mainData, detailData, mainFields });
    },
    mapPropsToFields(props) {
        //console.log(props)
        return props.orderFields || {};
    }
})(Card);

const mapStateToProps = (state, props) => {
    const { card } = state;
    console.log("card", card);
    return {
        istabinline: props.location.query.istabinline,
        billid: card.billid ? card.billid : (props.location.query.billid ? props.location.query.billid : ""),
        formId: props.location.query.formId ? props.location.query.formId : "0",
        modeId: props.location.query.modeId ? props.location.query.modeId : "0",
        type: card.modeType ? card.modeType : (props.location.query.type ? props.location.query.type : "0"),
        tabcount: card.tabcount ? card.tabcount : props.location.query.tabcount,
        viewfrom: props.location.query.viewfrom ? props.location.query.viewfrom : "",
        opentype: props.location.query.opentype ? props.location.query.opentype : "0",
        customid: props.location.query.customid ? props.location.query.customid : "0",
        fromSave: props.location.query.fromSave ? props.location.query.fromSave : "0",
        iscreate: props.location.query.iscreate ? props.location.query.iscreate : "",
        templateid: props.location.query.templateid ? props.location.query.templateid : "0",
        isfromTab: props.location.query.isfromTab ? props.location.query.isfromTab : "0",
        tabid: props.location.query.tabid ? props.location.query.tabid : "",
        loading: card.loading ? card.loading : "loading",
        isRight: card.isRight,
        isEdit: card.isEdit,
        isexcel: card.isexcel,
        datajson: card.datajson,
        orderlyjson: card.orderlyjson,
        modeInfo: card.modeInfo,
        layoutid: card.layoutid ? card.layoutid : props.location.query.layoutid,
        uploadfieldids: card.uploadfieldids,
        trrigerdetailbuttonfield: card.trrigerdetailbuttonfield,
        jsStr: card.jsStr,
        htmlHiddenElementsb: card.htmlHiddenElementsb,
        needcheck: card.needcheck,
        selectfieldvalue: card.selectfieldvalue,
        isMapLayout: card.isMapLayout,
        hasHtmlMode: card.hasHtmlMode,
        formhtml: card.formhtml,
        layoutversion: card.layoutversion,
        layoutcss: card.layoutcss,
        isImportDetail: card.isImportDetail,
        modename: card.modename,
        modedesc: card.modedesc,
        custompage: card.custompage,
        mainFields: card.mainFields,
        detailTable: card.detailTable,
        detailTableSize: (card.detailData || { detailRowSize: 0 }).detailRowSize,
        mainData: card.mainData,
        detailData: card.detailData,
        rightmenu: card.rightMenu,
        modeField: card.modeField,
        showReply: card.showReply,
        replyList: card.replyList,
        replyFieldList: card.replyFieldList,
        replyModeInfo: card.replyModeInfo,
        replyData: card.replyData,
        replyType: card.replyType ? card.replyType : "0",
        showType: card.showType,
        replySearchData: card.replySearchData ? card.replySearchData : { content: "", operatorid: "", createdateselect: "0", createdatefrom: "", createdateto: "", floorNum: "" },
        top: card.top ? card.top : "0",
        replyIndex: card.replyIndex,
        replyListData: card.replyListData ? card.replyListData : {},
        loadtimes: (card.mainFields || { loadtimes: 0 }).loadtimes,
        showImport: card.showImport,
        excelData: card.excelData ? card.excelData : new Array(),
        showBottom: card.showBottom,
        showX: card.showX,
        showY: card.showY,
        replyShowType: card.replyShowType,
        dataIndex: card.dataIndex,
        total: card.total,
        current: card.current,
        pagesize: card.pagesize,
        showShare: card.showShare,
        shareData: card.shareData ? card.shareData : { shareType: "1", rightType: "1", isRoleLimited: "0", rolelevel: "3", showlevel: "10", joblevel: "3" },
        shareDataList: card.shareDataList,
        selectedRowKeys: card.selectedRowKeys ? card.selectedRowKeys : [],
        showQr: card.showQr,
        showBar: card.showBar
    }
}
mapDispatchToProps = (dispatch) => {
    return {
        actions: bindActionCreators({ ...Actions, ...formAction }, dispatch)
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(Card);